package com.hup.utils.swing.customView;

import com.hup.utils.commons.ListUtil;
import com.hup.utils.commons.hardware.ScreenUtil;
import com.hup.utils.swing.customView.ScreenScaleComboBox.ScaleModel;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;

import javax.swing.*;
import java.util.Objects;

/**
 * 缩放比例下拉控件;
 * 系统改变比例后,要重启程序才能获取最新的比例;
 * @author hugan
 * @date 2020/4/19
 */
@Log4j2
public class ScreenScaleComboBox extends JComboBox<ScaleModel> {

    public ScreenScaleComboBox() {
        DefaultComboBoxModel<ScaleModel> model = new DefaultComboBoxModel<>();
        Integer curSystemScale = ScreenUtil.getScreenScale();
        for (ScaleModel scaleModel : ScaleModel.values()) {
            scaleModel.isDefault = Objects.equals(scaleModel.scale, curSystemScale);
            scaleModel.initText();
            model.addElement(scaleModel);
            if (scaleModel.isDefault) {
                model.setSelectedItem(scaleModel);
            }
        }
        //如果无查询到系统当前的比例,会在首次model.addElement时选中第一项
        super.setModel(model);
    }

    @Override
    public ScaleModel getSelectedItem() {
        return (ScaleModel) super.getSelectedItem();
    }

    /**
     * 要保证不会设置本控件 为无选中状态
     */
    public int getSelectedValue() {
        return getSelectedItem().scale;
    }

    /**
     * 要保证不会设置本控件 为无选中状态
     */
    public void setSelectedValue(int scale) {
        ScaleModel scaleModel = ListUtil.get(ScaleModel.values(), param -> param.scale == scale);
        setSelectedItem(scaleModel);
    }

    public enum ScaleModel {
        _100(100),
        _125(125),
        _150(150),
        _175(175),
        _200(200);

        public final int scale;
        @Getter
        private boolean isDefault;
        private String cbText;

        ScaleModel(int scale) {
            this.scale = scale;
        }

        /**
         * 初始化选项的文本;
         * 实际使用中,下拉/鼠标悬浮等时,都是通过toString频繁获取文本的;
         */
        private void initText() {
            cbText = isDefault ? scale + "%(默认)" : scale + "%";
        }

        @Override
        public String toString() {
            return cbText;
        }
    }

}
